var util = require('../../utils/util.js');
const cryptoJs = require('../../utils/cryptoJs.js');
var userInfoService = require('../../data/userInfoService.js');
var keyService = require('../../data/keyService.js');
var defaultData = require('../../data/defaultData.js');
const globalData = getApp().globalData;

Page({
  data: {
    userInfo: undefined,
    fingerPrint: false,
    autoCloud: false,
    nickName: '',
    avatarUrl: '',

    modalVisible: false,
    autofocus: false,
    modalTitle: '',
    modalTips: '',
    modalType: '',
    inputValue: ''
  },
  //用户登陆
  userInfoBind: function() {
    if (!globalData.isLogin) {
      userInfoService.getWxUserOpenID(globalData).then(res => {
        return this.getWxUserInfo();
      }).catch(er => {
        util.showToast('登录失败，请重试！');
      });
    } else {
      this.getWxUserInfo();
    }
  },
  getWxUserInfo: function() {
    return userInfoService.getWxUserInfo(globalData).then(res => {
      if (res = undefined || res == '') //用户未授权信息
        return;

      this.setData({
        nickName: globalData.userInfo.nickName,
        avatarUrl: globalData.userInfo.avatarUrl
      })
      let localJsonData = util.getStorageData(globalData.localJsonName);
      localJsonData.time = new Date().getTime();
      localJsonData.userInfo = globalData.userInfo;
      util.setStorageData(globalData.localJsonName, localJsonData);
      if (globalData.userInfo.isCloudSyn) { //开启了云同步
        util.setCloudDbData(globalData.cloudJsonName, localJsonData).catch(err => {
          console.error(err);
          util.showToast('登录失败，请重试！');
        });
      }
    }).catch(er => {
      util.showToast('登录失败，请重试！');
    });
  },
  //自定义分类
  categoryBind: function() {
    if (globalData.password == '') {
      util.showToast('必须输入主密码才能操作！');
      return;
    }
    util.navigateTo('childpages/category/category')
  },
  //设置主密码
  passwordBind: function() {
    if (globalData.password == '') {
      util.showToast('必须输入主密码才能操作！');
      return;
    }
    util.navigateTo('childpages/password/password')
  },
  //指纹设置
  fingerPrintChange(event) {
    const that = this;
    if (globalData.password == '') {
      wx.showModal({
        title: '必须输入主密码才能操作！',
        content: '',
        showCancel: false,
        success(res) {
          that.setData({
            fingerPrint: false
          })
        }
      });
      return;
    }

    if (event.detail.value) {
      const option = {
        title: '确认开启指纹？',
        content: '开启指纹后将可以使用指纹作为主密码',
        success(res) {
          if (!res.confirm) { //用户取消了
            that.setData({
              fingerPrint: false
            })
            return;
          }
          const option = {
            success: () => {
              globalData.authenPassword = globalData.password;
              util.setStorageData(globalData.localConfigName, globalData);
              util.showToast('开启成功！');
            },
            authentFail: (err) => {
              that.setData({
                fingerPrint: false
              })
              if (err.errCode != 90008) { //认证时，90008：用户点击了取消
                util.showToast('开启失败！');
              }
            },
            enrolledFail: (err) => {
              that.setData({
                fingerPrint: false
              })
            },
            supportFail: (err) => {
              that.setData({
                fingerPrint: false
              })
            }
          }
          util.checkIsSupportSoterAuthentication(option);
        }
      }
      wx.showModal(option);
    } else {
      const option = {
        title: '确认关闭指纹？',
        content: '关闭指纹后将不可以使用指纹当主密码',
        success(res) {
          if (!res.confirm) { //用户取消了
            that.setData({
              fingerPrint: true
            })
            return;
          }
          const checkOption = {
            success: (res) => {
              globalData.authenPassword = '';
              util.setStorageData(globalData.localConfigName, globalData);
              util.showToast('关闭成功！');
              return;
            },
            authentFail: (err) => {
              that.setData({
                fingerPrint: true
              })
              if (err.errCode != 90008) { //认证时，90008：用户点击了取消
                util.showToast('指纹认证失败！');
              }
              return;
            }
          };
          util.checkIsSoterEnrolledInDevice(checkOption);
        }
      }
      wx.showModal(option);
    }
  },
  //开启云同步
  autoCloudChange: function(event) {
    const that = this;
    if (!globalData.isLogin || !globalData.hasInfo || globalData.password == '') {
      wx.showModal({
        title: '云同步需要账号登陆！',
        content: '云同步需要登陆账号，并且已验证主密码！',
        showCancel: false,
        success(res) {
          that.setData({
            autoCloud: false
          })
        }
      });
      return;
    }

    if (event.detail.value) {
      const option = {
        title: '确认开启云同步？',
        content: '开启云同步将自动同步加密数据到云端',
        success(res) {
          if (!res.confirm) { //用户取消了
            that.setData({
              autoCloud: false
            })
            return;
          }

          const localJsonData = util.getStorageData(globalData.localJsonName);
          localJsonData.userInfo.isCloudSyn = true;
          util.setCloudDbData(globalData.cloudJsonName, localJsonData).then(res => {
            globalData.userInfo.isCloudSyn = true;
            util.setStorageData(globalData.localConfigName, globalData);
            util.setStorageData(globalData.localJsonName, localJsonData);
            util.showToast('开启成功！');
          }).catch(err => {
            console.error(err);

            that.setData({
              autoCloud: false
            })
            util.showToast('开启失败！');
          });
        }
      }
      wx.showModal(option);
    } else {
      const option = {
        title: '确认关闭云同步？',
        content: '关闭云同步将删除云端所有数据',
        success(res) {
          if (!res.confirm) { //用户取消了
            that.setData({
              autoCloud: true
            })
            return;
          }

          util.removeCloudDbData(globalData.cloudJsonName).then(res => {
            globalData.userInfo.isCloudSyn = false;
            util.setStorageData(globalData.localConfigName, globalData);
            util.showToast('关闭成功！');
          }).catch(err => {
            console.error(err);
            that.setData({
              autoCloud: true
            });
            util.showToast('关闭失败！');
          });
        }
      };
      wx.showModal(option);
    }
  },
  //原文导出
  textExportBind: function(event) {
    if (globalData.password == '') {
      util.showToast('必须输入主密码才能操作！');
      return;
    }
    util.navigateTo('childpages/dataexport/dataexport?exportType=1');
  },
  //格式化导出
  formatInputBind: function(event) {
    if (globalData.password == '') {
      util.showToast('必须输入主密码才能操作！');
      return;
    }
    util.navigateTo('childpages/dataexport/dataexport?exportType=2');
  },
  //格式化导入
  formatExportBind: function(event) {
    if (globalData.password == '') {
      util.showToast('必须输入主密码才能操作！');
      return;
    }
    util.navigateTo('childpages/dataexport/dataexport?exportType=3');
  },

  //输入框
  inputInputBind: function(event) {
    this.setData({
      inputValue: event.detail.value
    })
  },
  //重置弹出框
  initModal: function() {
    this.setData({
      modalVisible: false,
      autofocus: false,
      modalTitle: '',
      modalTips: '',
      modalType: '',
      inputValue: ''
    })
  },
  //弹出框 取消
  cancelBind: function(event) {
    this.initModal();
  },
  //弹出框 确定
  okBind: function(event) {
    const pwd = this.data.inputValue;
    const modalType = this.data.modalType;

    if (pwd == undefined || pwd == '') {
      util.showToast("请输入主密码！");
      return;
    }

    const enPassword = globalData.userInfo.enPassword;
    const md5Pwd = cryptoJs.MD5Encrypt(pwd);
    if (enPassword !== md5Pwd) {
      util.showToast("输入的主密码不正确，请重新输入！")
      return;
    }
    if (modalType == 'clearData') {
      this.clearData();
      this.initModal();
      return;
    }
    if (modalType == 'formatData') {
      this.formatData();
      this.initModal();
      return;
    }
  },
  //清空数据
  clearDataBind: function() {
    if (globalData.password == '') {
      util.showToast('必须输入主密码才能操作！');
      return;
    }

    this.setData({
      autofocus: true,
      modalVisible: true,
      modalTitle: '确认清空所有数据?',
      modalTips: '你会失去所有钥匙的数据',
      modalType: 'clearData',
      inputValue: ''
    });

    //this.clearData();
  },
  clearData: function() {
    //本地缓存文件
    const localJsonData = util.getStorageData(globalData.localJsonName);
    localJsonData.time = new Date().getTime();
    localJsonData.key = [];
    //持久化
    util.setStorageData(globalData.localJsonName, localJsonData);

    if (!globalData.userInfo.isCloudSyn) {
      util.showToast("清除全部数据成功！");
      return;
    }
    util.setCloudDbData(globalData.cloudJsonName, localJsonData).then(res => {
      util.showToast("清除全部数据成功！");
    }).catch(err => {
      console.error(err);
      util.showToast("清除全部数据失败！");
    });
  },
  //格式化数据
  formatDataBind: function() {
    if (globalData.password == '') {
      util.showToast('必须输入主密码才能操作！');
      return;
    }

    this.setData({
      autofocus: true,
      modalVisible: true,
      modalTitle: '确认格式化应用?',
      modalTips: '你将会格式化应用所有数据',
      modalType: 'formatData',
      inputValue: ''
    });

    //this.formatData();
  },
  formatData: function() {
    //准备数据
    const defaultPassward = '123456';
    const nowTime = new Date().getTime();
    const oldIsCloudSyn = globalData.userInfo.isCloudSyn; //旧值：是否开启云同步；
    const localJsonData = util.getStorageData(globalData.localJsonName);

    //重置userInfo
    const userInfo = defaultData.getDefaultUserInfo();
    userInfo.openID = localJsonData.userInfo.openID;
    userInfo.unionID = localJsonData.userInfo.unionID;
    userInfo.enPassword = cryptoJs.MD5Encrypt(defaultPassward);
    userInfo.time = nowTime;

    //本地缓存文件
    localJsonData.time = nowTime;
    localJsonData.category = defaultData.getDefaultCategory();
    localJsonData.key = [];
    localJsonData.userInfo = userInfo;

    //globalData数据
    globalData.userInfo = userInfo;
    globalData.isLogin = false;
    globalData.hasInfo = false;
    globalData.password = defaultPassward;
    globalData.authenPassword = "";
    globalData.time = nowTime;

    const newLocalJsonData = keyService.enJsonData(localJsonData, globalData.password); //加密
    //持久化
    util.setStorageData(globalData.localJsonName, newLocalJsonData);
    util.setStorageData(globalData.localConfigName, globalData);

    if (!oldIsCloudSyn) {
      util.showToast("格式化成功！");
      this.setData({
        fingerPrint: globalData.authenPassword != '',
        autoCloud: globalData.userInfo.isCloudSyn,
        nickName: globalData.userInfo.nickName,
        avatarUrl: globalData.userInfo.avatarUrl
      });
      return;
    }
    util.removeCloudDbData(globalData.cloudJsonName).then(res => {
      util.showToast("格式化成功！");
      this.setData({
        fingerPrint: globalData.authenPassword != '',
        autoCloud: globalData.userInfo.isCloudSyn,
        nickName: globalData.userInfo.nickName,
        avatarUrl: globalData.userInfo.avatarUrl
      });
    }).catch(err => {
      console.error(err);
      util.showToast('本地数据格式化成功，云数据格式化失败!');
    });
  },
  //指南
  guideBind: function() {
    util.navigateTo('childpages/guide/guide')
  },
  //常见问题
  problemBind: function() {
    util.navigateTo('childpages/problem/problem')
  },
  //更新记录
  updateLogBind: function() {
    util.navigateTo('childpages/updatelog/updatelog')
  },
  // 关于
  aboutBind: function() {
    util.navigateTo('childpages/about/about')
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      fingerPrint: globalData.authenPassword != '',
      autoCloud: globalData.userInfo.isCloudSyn,
      nickName: globalData.userInfo.nickName,
      avatarUrl: globalData.userInfo.avatarUrl
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  }
});